<template>
	<view class="">
		<canvas canvas-id="waterMarkCanvas" v-if="waterMarkParams.display"
			:style="{ height: `${waterMarkParams.canvasHeight}px`,width: `${waterMarkParams.canvasWidth}px`, position: 'fixed', left: '9999px',}">
		</canvas>
		<uv-upload class="margin-top-sm" :fileList="fileList1" name="1" multiple :deletable="deletable" :maxCount="maxCount" uploadIcon="plus" :disabled="disabled"
			uploadIconColor="#006BFE" :uploadText="uploadText" @afterRead="afterRead" @delete="deletePic"
			:previewFullImage="true"></uv-upload>
	</view>

</template>

<script>
	const weekDay = ['日', '一', '二', '三', '四', '五', '六']
	export default {
		props: {
			value: [String, Object, Array],
			disabled: {
				type: Boolean,
				default: false
			},
			deletable: {
				type: Boolean,
				default: true
			},
			maxCount: {
				type: Number,
				default: 3
			},
			uploadText: {
				type: String,
				default: '图片上传'
			},
		},
		data() {
			return {
				waterMarkParams: {
					display: false, // 控制 canvas 创建与销毁
					canvasWidth: 300, // 默认宽度
					canvasHeight: 225, // 默认高度
					contentHeight: 210, // 将要被绘制到图像中的矩形的高度(px)
				},
				fileList1: [],
				uploadList: [],
				headers: {
					Authorization: "Bearer " + uni.getStorageSync('token'),
				},
			}
		},
		watch: {
			value: {
				handler(val) {
					if (val) {
						// 首先将值转为数组
						const list = Array.isArray(val) ? val : this.value.split(",");
						this.fileList1 = [];
						this.uploadList = [];
						for (let item of list) {
							if (!item) continue; //空图片不显示
							if (typeof item === "string") {
								item = {
									name: item,
									url: `${this.$hd.baseUrl}/common/file/${item}`,
									id: item
								};
								// 通过id获取图片
								// this.$http.get('/common/file/'+item).then(res => {
								// 	console.log(11,res)
								// })
								//映射路径不包含/api
								// if (item.indexOf(this.$hd.baseUrl) === -1) {
								// 	if (!item.includes("/upload-file")) {
								// 		item = {
								// 			name: this.$hd.baseUrl + this.uploadBasePrefix + item,
								// 			url: this.$hd.baseUrl + this.uploadBasePrefix + item,
								// 		};
								// 	} else if (item.includes("/upload/")) {
								// 		item = {
								// 			name: this.$hd.baseUrl + item,
								// 			url: this.$hd.baseUrl + item,
								// 		};
								// 	} else {
								// 		item = {
								// 			name: this.$hd.baseUrl + item,
								// 			url: this.$hd.baseUrl + item,
								// 		};
								// 	}
								// } else {
								// 	item = {
								// 		name: item,
								// 		url: item
								// 	};
								// }
							} else if (typeof item === "object") {
								item.url = this.$hd.baseUrl + this.uploadBasePrefix + item.uploadPath + "/" + item.name
							}
							console.log("item", item);
							this.fileList1.push(item);
							this.uploadList.push(item);
						}
					} else {
						this.fileList1 = [];
						this.uploadList = [];
						return [];
					}
				},
				deep: true,
				immediate: true,
			},
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.uploadList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map(async (item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				// for (let i = 0; i < lists.length; i++) {
        // 	const item =
				// }
				for (let i = 0; i < lists.length; i++) {
					const imgFileArr = await this.callAddWaterMark(lists[i].url)
					// console.log('imgFileArr', imgFileArr)
					const result = await this.uploadFilePromise(imgFileArr)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
					this.uploadList.push(result.data)
				}
				const pathArr = this.uploadList.map(item => (item.id))
				this.$emit("input", pathArr.join(','));
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$hd.baseUrl + '/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							// user: 'test'
						},
						header: {
							Authorization: "Bearer " + uni.getStorageSync('token'),
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						}
					});
				})
			},
			// 因为有可能在相册中选择多个图片，所以这里要依次生成水印
			async callAddWaterMark(imgPathArr) {
        const config = await this.$hd.sysConfig()
        if (config['hui-da.imageWatermark'] && config['hui-da.imageWatermark'] === 'true') {
          let results = await this.addWaterMark(imgPathArr)
          // if(imgPathArr.length > 0) {
          //   let addIndex = 0
          //   while(addIndex < imgPathArr.length) {
          //     const tempFilePath = await this.addWaterMark(imgPathArr[addIndex])
          //     results.push(tempFilePath)
          //     addIndex = addIndex + 1
          //   }
          // }
          return results
        }
        return imgPathArr
			},
			// 添加水印
			addWaterMark(src) {
				return new Promise((resolve, reject) => {
					// 获取图片信息，配置 canvas 尺寸
					uni.getImageInfo({
						src,
						success: res => {
							// console.log('图片信息', res)
							// 修复部分手机(如红米9)手机屏幕比较窄拍摄出来的图片水印压缩着覆盖的问题
							this.waterMarkParams.canvasWidth = Math.max(res.width, 886);
							this.waterMarkParams.canvasHeight = Math.max(res.height, 886);
							this.waterMarkParams.display = true
							// console.log('当前图片信息waterMarkParams：', this.waterMarkParams);
							// 等待 canvas 元素创建
							this.$nextTick(() => {
								let context = uni.createCanvasContext("waterMarkCanvas", this);
								/* 绘制 */
								const {
									canvasWidth,
									canvasHeight,
									contentHeight
								} = this.waterMarkParams
								// 绘制前清空画布
								context.clearRect(0, 0, canvasWidth, canvasHeight);
								// 将图片src放到cancas内，宽高必须为图片大小
								context.drawImage(src, 0, 0, canvasWidth, canvasHeight,
									canvasWidth, canvasHeight);
								// 设置边框的透明度
								context.setGlobalAlpha(0.3);
								context.beginPath();
								// 绘制底部的白色背景
								context.rect(0, canvasHeight - contentHeight, canvasWidth,
									contentHeight);
								context.setFillStyle("#000000");
								context.setGlobalAlpha(0.3);
								context.fill();
								// 设置文字的透明度
								context.setGlobalAlpha(1);
								// 3.绘制底部的文字
								context.setFontSize(32);
								context.setTextAlign("left");
								context.setFillStyle("white");
								context.fillText(
									`${this.$hd.position.addr}`,
									50, canvasHeight - 140);
								context.fillText(
									`北纬${this.$hd.position.lat} 东经${this.$hd.position.lng}`,
									50, canvasHeight - 90);
								context.fillText(
									`${this.$uv.timeFormat(new Date(), "yyyy-mm-dd hh:MM:ss")} 星期${weekDay[new Date().getDay()]}`,
									50, canvasHeight - 40);
								// 一定要加上一个定时器否则进入到页面第一次可能会无法正常拍照，后几次才正常
								setTimeout(() => {
									// 本次绘画完重开开始绘画，并且在绘画完毕之后再保存图片，不然页面可能会出现白屏等情况
									context.draw(false, () => {
										// console.log('!!!!!开始绘画', canvasWidth,
										// 	canvasHeight);
										uni.canvasToTempFilePath({
											canvasId: "waterMarkCanvas",
											fileType: "jpg",
											width: canvasWidth,
											height: canvasHeight,
											destWidth: canvasWidth,
											destHeight: canvasHeight,
											success: ({
												tempFilePath
											}) => {
												console.log('绘制成功',
													tempFilePath
												);
												this.waterMarkParams
													.display =
													false
												resolve(
													tempFilePath
												)
											},
											fail: err => {
												reject(err)
												console.log(err);
											}
										}, this)
									})
								}, 1000);
							})
						}
					})
				})
			},
		},
	}
</script>

<style>
</style>
